#!/usr/bin/python

from __future__ import division, print_function
from rsl import RSL
import math
import readline
import sys

class Compiler():
	def compileProgress(self, line, total):
		#print("Called")
		while (self.compile_last_progress < math.ceil(20 / total * line)):
			sys.stdout.write("#")
			sys.stdout.flush()
			self.compile_last_progress += 1

	def compile(self):
		interpreter = RSL();
		interpreter.engine.before_error = "X\n"
		
		try:
			filename = sys.argv[1]
		except:
			filename = raw_input("Please enter an RSL filename: ")
		
		try:
			sys.stdout.write("Reading file... ")
			f = open(filename)
			code = f.read()
			f.close()
			sys.stdout.write("done.\n")
		except IOError:
			print("Invalid filename entered.")
			self.compile()
			return
		
		# Now compile the code
		sys.stdout.write("                       /------------------\\\n")
		sys.stdout.write("Compiling to bytecode: ")
		self.compile_last_progress = 0;
		interpreter.filename = filename
		try:
			bytecode = interpreter.interpretCodeProgressCallback(code, self.compileProgress)
		except:
			sys.stdout.write("\n")
			raise
		if (self.compile_last_progress < 20):
			while (self.compile_last_progress < 20):
				sys.stdout.write("#")
				sys.stdout.flush()
				self.compile_last_progress += 1
		
		self.compile_last_progress = 0;
		interpreter.engine.before_error = ""
		sys.stdout.write("\n")
		
		
		# Get a new filename before running this
		n = filename.rfind(".")
		if (n == -1):
			bfilename = filename + ".rsb"
			ofilename = filename + ".rso"
		else:
			bfilename = filename[:n] + ".rsb"
			ofilename = filename[:n] + ".rso"
		print("Main bytecode has been saved to: " + bfilename)
		print("Class and function bytecode has been saved to: " + ofilename)
		
		print("Executing main bytecode: ")
		print("============================================")
		
		
		interpreter.runByteCode(bytecode, bfilename, ofilename)
	
print("Welcome to the RSL Commander.")
com = Compiler()
com.compile()